package com.primestone.cim.executeenddevicecontrols.async;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.primestone.cim.entities.tmp.ResEndDeviceControls;
import com.primestone.cim.util.StringUtil;

/**
 * Session Bean implementation class TmpTableEJBBean
 */
@TransactionManagement( TransactionManagementType.CONTAINER )
@Stateless(mappedName = StringUtil.TMPTABLEEJB_MAPPED_NAME, name = StringUtil.TMPTABLEEJB_NAME)
public class TmpTableEJBBean implements TmpTableEJBLocal {
	
	@PersistenceContext( unitName = StringUtil.PERSISTENCE_UNIT )
	protected EntityManager em;

    /**
     * Default constructor. 
     */
    public TmpTableEJBBean() {
        // Auto-generated constructor stub
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void saveEndDeviceControls(ResEndDeviceControls resEndDeviceControl) {
		em.persist(resEndDeviceControl);
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void saveEndDeviceControls(List<ResEndDeviceControls> resEndDeviceControls) {
    	for (ResEndDeviceControls resEndDeviceControl : resEndDeviceControls) {
			em.persist(resEndDeviceControl);
		}
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public ResEndDeviceControls findControlOperationResultByTicket(String ticket) {
    	try {
            Query query = em.createNamedQuery( "ResEndDeviceControls.findByTicket" );
            query.setParameter( "ResEndDeviceControls_ticket", ticket );

            return ( ResEndDeviceControls )query.getSingleResult();

        } catch( NoResultException e ) {
            return null;
        }
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void deleteControlOperationResult(ResEndDeviceControls resEndDeviceControl) {
    	em.remove( em.merge( resEndDeviceControl ) );
    }

}
